#!/bin/bash
# ndb_mgmd   Startup script for the ndb_mgmd
# chkconfig: 2 50 22

ndb_mgmd=/usr/local/mysql/bin/ndb_mgmd
config_file=/usr/local/mysql/config.ini

if ! test -x $ndb_mgmd; then
    echo "Can't execute $ndb_mgmd"
    exit 1
fi

initial() {
    pids=`ps aux | grep -iv "grep" | grep -i "$ndb_mgmd" | wc -l`
    if [ $pids -eq 0 ]; then
        $ndb_mgmd -f $config_file --reload
        echo "NDB_MGM daemon started"
    else
        echo "NDB_MGM daemon is already running."
    fi
}

start() {
    pids=`ps aux | grep -iv "grep" | grep -i "$ndb_mgmd" | wc -l`
    if [ $pids -eq 0 ]; then
    	$ndb_mgmd -f $config_file

        echo "NDB_MGM daemon started"
    else
    	echo "NDB_MGM daemon is already running."
    fi
}

stop() {
    pids=`ps aux | grep -iv "grep" | grep -i "$ndb_mgmd" | wc -l`
    if [ $pids -ne 0 ]; then

        pids=`ps aux | grep -iv "grep" | grep -i "$ndb_mgmd" | awk '{ print $2 }'`
    	for pid in $(echo $pids); do
            kill $pid 2> /dev/null
    	done

        sleep 3

    	pids=`ps aux | grep -iv "grep" | grep -i "$ndb_mgmd" | wc -l`
    	if [ $pids -eq 0 ]; then
            echo "NDB_MGM daemon stopped."
        else
       	    echo "Could not stop NDB_MGM daemon."
        fi
    else
    	echo "NDB_MGM daemon is not running."
    fi
}

case "$1" in
    start)
    	start
    	;;
    stop)
    	stop
    	;;
    initial)
    	initial
    	;;
    restart)
    	stop
        sleep 3
    	start
    	;;
    *)
    	echo $"Usage: $0 {start|stop|restart|initial}" >&2
    	;;
esac

exit 0
